import api from '../../mock/index.js'
import { getArticleCategory, getArticleList, getArticleDetail, submitIndexInfo, getIndexDialogFlag } from '../../api/index.js'
	
const store = {
	state: {
		activeCate: 0, // 选中的分类
		categoryList: [], // 分类列表
		list: [], // 列表
		page: 1, // 从第一页开始请求
		isEnd: false, // 是否到底
		needSetInfo: true, // 首页是否需要弹窗填写信息
	},
	
	mutations: {
		upateCurrCate(state, cate) {
			state.activeCate = cate
		},
		
		updataCateList(state, list) {
			state.categoryList = list
		},
		
		updateList(state, list) {
			state.list = list
		},
		
		updatePage(state, page) {
			state.page = page
		},
		
		updateIsEnd(state, isEnd) {
			state.isEnd = isEnd
		},
		
		needSetInfo(state, needSetInfo) {
			state.needSetInfo = needSetInfo
		}
	},
	
	actions: {
		// 获取是否需要弹窗提示收集信息
		async getDialogFlag({ commit }) {
			let res = await api.post(getIndexDialogFlag, {})
			commit('needSetInfo', res)
		},
		
		// 表单提交
		async submitInfo({ commit }, params = {}) {
			let res = await api.post(submitIndexInfo, params)
			commit('needSetInfo', res)
		},
		
		// 刷新
		reload({ dispatch, commit }) {
			commit('updatePage', 1)
			commit('updateList', [])
			commit('updateIsEnd', false)
			dispatch('getArticleListByCate')
		},
		
		// 请求下一页
		async getArticleListByCate({ commit, state }, param = {}) {
			let { list = [], currCateId, page = 1, isEnd } = state
			param.page = page
			param.categoryId = currCateId
			
			// 没有下一页就不在请求
			if (isEnd) {
				return false
			}
			let res = await api.post(getArticleList, param)
			if (res.data.list.last_page >= page) {
				list = list.concat(res.data.list.data)
				commit('updatePage', page + 1)
			}
			commit('updateList', list)
			commit('updateIsEnd', res.data.list.last_page == page)
		},
		
		// 选中分类
		setCurrCate({ commit, dispatch }, id) {
			commit('upateCurrCate', id)
			dispatch('reload')
		},
		
		// 请求分类
		async getArticleCate({ commit, dispatch }) {
			let res = await api.post(getArticleCategory)
			if (res.data && res.data.list && res.data.list.length) {				
				commit('updataCateList', res.data.list)
				dispatch('setCurrCate', res.data.list[0].category_id)
			}
		},
		
		// 获取文章详情
		async getArticleDetailById(_, id) {
			let res = await api.post(getArticleDetail, {
				articleId: id
			})
			return res.data.detail
		}
	},
	namespaced: true
}

export default store
